#include "ImportThread.h"
#include "Platform.h"
#include <QFile>
#include <QCryptographicHash>
#include <QuaZip/quazip.h>
#include <QuaZip/JlCompress.h>


ImportThread::ImportThread(QString zipPath) : QThread(), zipPath(zipPath)
{

}

ImportThread::~ImportThread()
{

}

void ImportThread::run()
{
    auto zip_file = QFile(zipPath);
    if (!zip_file.exists())
    {
        emit handle(FileNotExists, 0, "");
        deleteLater();
        return;
    }

    if(!zip_file.open(QIODevice::ReadOnly))
    {
        emit handle(FileCannotOpen, 0, "");
        deleteLater();
        return;
    }

    int process_start = 0;
    int process_lenght = 0;
    // File Verification, Process 0~50
    process_start = 0;
    process_lenght = 50;
    emit handle(UpdateLabelAndPrcess, process_start, tr("file_verification").arg("0.00%"));

    auto hash = QCryptographicHash(QCryptographicHash::Algorithm::Md5);
    hash.reset();

    while(!zip_file.atEnd())
    {
        if(cancel)
        {
            deleteLater();
            return;
        }
        hash.addData(zip_file.read(8192));
        auto p = (double)zip_file.pos() / (double)zip_file.size();
        emit handle(UpdateLabelAndPrcess, p * process_lenght + process_start, tr("file_verification").arg(QString::number(p * 100, 'f', 2) + "%"));
    }
    zip_file.close();

    auto md5 = hash.result().toHex();
    auto md5_right = "be4b9059a60a9dded729dba2814bb4e6";
    if(md5 != md5_right)
    {
        emit handle(FileVerificationFailed, 0, "");
        deleteLater();
        return;
    }

    // File Extraction, Process 50~100
    process_start = 50;
    process_lenght = 100 - 50;
    emit handle(UpdateLabelAndPrcess, process_start, tr("file_extraction").arg("0.00%", ""));
    QuaZip zip(zipPath);
    if(!zip.open(QuaZip::mdUnzip))
    {
        emit handle(FileCannotOpen, 0, "");
        deleteLater();
        return;
    }

    auto file_list = zip.getFileNameList();
    for(int index = 0; index < file_list.size(); index++)
    {
        if(cancel)
        {
            deleteLater();
            return;
        }
        auto p = (double)index / (double)file_list.size();
        auto& file_name = file_list.at(index);
        emit handle(UpdateLabelAndPrcess, p * process_lenght + process_start, tr("file_extraction").arg((QString::number(p * 100, 'f', 2) + "%"), file_name));
        QString filePath = Platform::GetOraContentDir() + file_name;
        JlCompress::extractFile(&zip, file_name, filePath);
    }

    emit handle(UpdateLabelAndPrcess, 100, tr("finished_note"));
    emit handle(Finished, 0, "");
    deleteLater();
}

void ImportThread::Cancel()
{
    cancel = true;
}




























